package com.yanqu.road.server.manager.activity.apprentice;

import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.apprentice.config.*;
import com.yanqu.road.entity.activity.apprentice.enums.ApprenticeProjectTypeEnum;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.logic.bussiness.DaoHelper;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.logic.helper.ActivityHelper;
import com.yanqu.road.server.CrossBaseServer;
import com.yanqu.road.server.TempCrossMgr;
import com.yanqu.road.server.manager.activity.ActivityMgr;
import com.yanqu.road.server.manager.activity.apprentice.handler.ApprenticeProjectHandler;
import com.yanqu.road.server.manager.activity.apprentice.handler.impl.*;
import com.yanqu.road.server.manager.activity.apprentice.handler.param.ApprenticeCountSortAddRateReq;
import com.yanqu.road.server.manager.activity.apprentice.handler.param.ApprenticeCountTalentAddRateReq;
import com.yanqu.road.server.manager.activity.apprentice.handler.param.ApprenticeDoProjectReq;
import com.yanqu.road.server.manager.activity.apprentice.handler.param.ApprenticeDoProjectResp;
import com.yanqu.road.server.manager.activity.doublespring.CrossDoubleSpringActivity;
import com.yanqu.road.server.manager.activity.hsisland.CrossHsIslandActivity;
import com.yanqu.road.server.manager.union.activitygroup.Cross2UnionActivityGroupMgr;
import com.yanqu.road.utils.date.DateHelper;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class CrossApprenticeMgr extends TempCrossMgr {

    /**
     * 活动MAP
     */
    private static Map<Integer, CrossApprenticeActivity> activityMap = new ConcurrentHashMap<>();

    /**
     * 执行项目策略MAP
     */
    private static Map<Integer, ApprenticeProjectHandler> handlerMap = new ConcurrentHashMap<>();
    static {
        handlerMap.put(ApprenticeProjectTypeEnum.TYPE_1.getType(), new ApprenticeDoProjectType1Handler());
        handlerMap.put(ApprenticeProjectTypeEnum.TYPE_2.getType(), new ApprenticeDoProjectType2Handler());
        handlerMap.put(ApprenticeProjectTypeEnum.TYPE_3.getType(), new ApprenticeDoProjectType3Handler());
        handlerMap.put(ApprenticeProjectTypeEnum.TYPE_4.getType(), new ApprenticeDoProjectType4Handler());
        handlerMap.put(ApprenticeProjectTypeEnum.TYPE_5.getType(), new ApprenticeDoProjectType5Handler());
        handlerMap.put(ApprenticeProjectTypeEnum.TYPE_6.getType(), new ApprenticeDoProjectType6Handler());
        handlerMap.put(ApprenticeProjectTypeEnum.TYPE_7.getType(), new ApprenticeDoProjectType7Handler());
        handlerMap.put(ApprenticeProjectTypeEnum.TYPE_8.getType(), new ApprenticeDoProjectType8Handler());
        handlerMap.put(ApprenticeProjectTypeEnum.TYPE_9.getType(), new ApprenticeDoProjectType9Handler());
        handlerMap.put(ApprenticeProjectTypeEnum.TYPE_10.getType(), new ApprenticeDoProjectType10Handler());
        handlerMap.put(ApprenticeProjectTypeEnum.TYPE_11.getType(), new ApprenticeDoProjectType11Handler());
        handlerMap.put(ApprenticeProjectTypeEnum.TYPE_12.getType(), new ApprenticeDoProjectType12Handler());
        handlerMap.put(ApprenticeProjectTypeEnum.TYPE_13.getType(), new ApprenticeDoProjectType13Handler());
        handlerMap.put(ApprenticeProjectTypeEnum.TYPE_14.getType(), new ApprenticeDoProjectType14Handler());
        handlerMap.put(ApprenticeProjectTypeEnum.TYPE_15.getType(), new ApprenticeDoProjectType15Handler());
    }

    @Override
    public boolean removeExpireData() throws Exception {
        Set<Integer> acSet = new HashSet<>();
        long nowTime = System.currentTimeMillis();
        for (Integer activityId : activityMap.keySet()) {
            CrossApprenticeActivity activity = activityMap.get(activityId);
            // 展示期过3天后移除内存
            if (activity == null || activity.getConfig() == null || activity.getConfig().getActivityInfo() == null ||
                    nowTime > activity.getConfig().getActivityInfo().getEndShowTime() * 1000 + 3 * DateHelper.DAY_MILLIONS) {
                acSet.add(activityId);
            }
        }
        for (int activityId : acSet) {
            activityMap.remove(activityId);
        }
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        reloadActivityConfig();
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        Map<Integer, ActivityInfo> activityInfoMap = ActivityMgr.getOpenCrossActivityMapByType(eActivityType.Apprentice.getValue());
        //活动加载进内存
        for (ActivityInfo activityInfo : activityInfoMap.values()) {
            if (ActivityHelper.activityInShowTime(activityInfo)) {
                getActivity(activityInfo.getActivityId());
            }
        }
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    @Override
    public boolean save() {
        for (CrossApprenticeActivity activity : activityMap.values()) {
            try {
                activity.save();
            }catch (Exception e){
                getLogger().error("apprentice activity {} save err", activity.getActivityId(), e.getCause());
            }
        }
        return true;
    }

    /**
     * 刷新配置
     */
    public static synchronized void reloadActivityConfig() {
        getLogger().info("CrossApprenticeMgr reloadConfig start");
        for (CrossApprenticeActivity activity : activityMap.values()) {
            //获取一下新的ActivityInfo
            ActivityInfo activityInfo = ActivityBussiness.getActivityInfoByActivityId(activity.getActivityId());
            if (activityInfo == null) {
                continue;
            }
            //构造活动配置
            ApprenticeConfig newConfigData = createConfig(activityInfo);
            //刷新配置信息
            activity.refreshConfig(newConfigData);
            getLogger().info("CrossApprenticeMgr reloadConfig success,activityId:{}", activityInfo.getActivityId());
        }
        getLogger().info("CrossApprenticeMgr reloadConfig end");
    }

    /**
     * create活动配置
     * @param activityInfo
     * @return
     */
    public static ApprenticeConfig createConfig(ActivityInfo activityInfo) {
        //获取活动config
        List<Integer> activityIdList = new ArrayList<>();
        activityIdList.add(activityInfo.getActivityId());
        //获取config
        Map<String, ActivityConfig> configMap = ActivityBussiness.getActivityConfigMap(activityIdList).get(activityInfo.getActivityId());
        //等级配置
        Map<Integer, ApprenticeLevelConfig> levelConfigMap = DaoHelper.getGenericConfigDaoImpl().getGenericConfigMap(activityInfo.getActivityId(), ApprenticeLevelConfig.class);
        //项目配置
        Map<Integer, ApprenticeProjectConfig> projectConfigMap = DaoHelper.getGenericConfigDaoImpl().getGenericConfigMap(activityInfo.getActivityId(), ApprenticeProjectConfig.class);
        //小考模版配置
        Map<Integer, ApprenticeModelConfig> modelConfigMap = DaoHelper.getGenericConfigDaoImpl().getGenericConfigMap(activityInfo.getActivityId(), ApprenticeModelConfig.class);
        //保底配置
        Map<Integer, ApprenticeHelpConfig> helpConfigMap = DaoHelper.getGenericConfigDaoImpl().getGenericConfigMap(activityInfo.getActivityId(), ApprenticeHelpConfig.class);
        //实例化活动配置
        return new ApprenticeConfig(activityInfo, configMap, levelConfigMap, projectConfigMap, modelConfigMap, helpConfigMap);
    }

    /**
     * 获取活动
     * @param activityId
     * @return
     */
    public static CrossApprenticeActivity getActivity(int activityId) {
        CrossApprenticeActivity activity = activityMap.get(activityId);
        if (activity != null) {
            return activity;
        }
        //初始化活动
        return initActivity(activityId);
    }

    /**
     * 初始化活动
     * @param activityId
     * @return
     */
    private static CrossApprenticeActivity initActivity(int activityId) {
        synchronized (activityMap) {
            CrossApprenticeActivity activity = activityMap.get(activityId);
            if (activity != null) {
                return activity;
            }
            //读配置 获取活动信息 保证有活动信息
            ActivityInfo activityInfo = ActivityMgr.getActivityInfoMayLoadDB(activityId);
            if (activityInfo == null) {
                return null;
            }
            //不在展示期（+3天）也不处理了
            if (!ActivityHelper.activityInShowTime(activityInfo)) {
                return null;
            }
            //创建配置
            ApprenticeConfig config = createConfig(activityInfo);
            //创建活动
            activity = new CrossApprenticeActivity(config);
            activityMap.put(activity.getActivityId(), activity);
            return activity;
        }
    }

    /**
     * 执行项目
     * @param req
     * @return
     */
    public static ApprenticeDoProjectResp doProject(ApprenticeDoProjectReq req) {
        ApprenticeProjectHandler handler = handlerMap.get(req.getType());
        if (handler != null) {
            return handler.doProject(req);
        }
        return null;
    }

    /**
     * 计算职业加成比例
     * @param req
     */
    public static void countTalentTypeAddRate(ApprenticeCountTalentAddRateReq req){
        ApprenticeProjectHandler handler = handlerMap.get(req.getType());
        if (handler != null) {
            handler.countTalentTypeAddRate(req);
        }
    }

    /**
     * 计算品质加成比例
     * @param req
     */
    public static void countSortTypeAddRate(ApprenticeCountSortAddRateReq req){
        ApprenticeProjectHandler handler = handlerMap.get(req.getType());
        if (handler != null) {
            handler.countSortTypeAddRate(req);
        }
    }

    /**
     * 预留修复数据方法
     */
    public static void repairHot() {
        for (CrossApprenticeActivity activity : activityMap.values()) {
            activity.repairHot();
        }
    }
}
